package org.swust.sysmonitorapp.service.handler;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.swust.sysmonitorapp.entity.HealthData;
import org.swust.sysmonitorapp.service.IHealthDataService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

@Slf4j
public class DevicePropertyHandler implements MessageHandler {

    private final IHealthDataService healthDataService;

    public DevicePropertyHandler(IHealthDataService healthDataService) {
        this.healthDataService = healthDataService;
    }

    @Override
    public void handle(JsonNode root) {
        try {
            JsonNode header = root.path("notify_data").path("header");
            JsonNode service = root.path("notify_data").path("body").path("services").get(0);
            JsonNode properties = service.path("properties");

            String eventTimeStr = service.path("event_time").asText();
            LocalDateTime eventTime;
            String remark = null;
            try {
                eventTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ISO_DATE_TIME);
            } catch (DateTimeParseException e) {
                log.warn("无效的 event_time 格式: {}", eventTimeStr);
                eventTime = LocalDateTime.now();
                remark = "Invalid event_time: " + eventTimeStr;
            }

            HealthData healthData = new HealthData();
            healthData.setDeviceId(header.path("device_id").asText());
            healthData.setHeartRate(properties.path("heart-rate").asInt());
            healthData.setBloodOxygen(BigDecimal.valueOf(properties.path("blood-oxygen").asDouble()));
            healthData.setMeasureTime(eventTime);
            healthData.setRemark(remark);
            healthData.setUserId(2L);

            healthDataService.save(healthData);
            log.info("健康数据保存成功: {}", healthData);

        } catch (Exception e) {
            log.error("处理 device.property 消息失败", e);
        }
    }
}
